package com.pay;

import com.alibaba.fastjson.JSON;
import com.pay.bean.PayBean;
import com.pay.bean.PayResult;
import com.pay.bean.UrlRequest;
import com.pay.util.MD5;
import com.pay.util.RandomUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import static com.pay.bean.GlobalData.*;

@WebServlet(name = "PayRequestServlet", urlPatterns = "/servlet/PayRequestServlet")
public class PayRequestServlet extends HttpServlet {

    static DateFormat sTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static DateFormat sMerchFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    //return post data
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String usrName = req.getParameter("usrName");
        String totOrdrAmt = req.getParameter("totOrdrAmt");
        String extParm = req.getParameter("extParm");
        Date date = new Date();
        String timeStamp = sTimeFormat.format(date);
        String merchordrno = sMerchFormat.format(date) + String.valueOf(RandomUtil.generateFourDigit());

        PayBean payBean = new PayBean();
        payBean.setAppId(APP_ID);
        payBean.setApiVer(API_VER);
        payBean.setPayType(PAY_TYPE);
        payBean.setScene(SCENE);
        payBean.setTerminal(TERMINAL);
        payBean.setFmt(FMT);
        payBean.setCharset(CHARSET);
        payBean.setSgnType(TYPE);
        payBean.setMerchOrdrNo(merchordrno);
        payBean.setTotOrdrAmt(totOrdrAmt);
        payBean.setNoteUrl(NOTE_URL);
        payBean.setRtnUrl(RTN_URL);
        payBean.setTimeStamp(timeStamp);
        payBean.setUsrName(usrName);
        payBean.setExtParm(extParm);
        String md5 = MD5.getMD5(composePayJsonStr(payBean));
        payBean.setSgn(md5);
        System.out.println("paybean " + payBean.toString());
        String retStr = UrlRequest.sendPost(URL_API, composePostStr(payBean));
        System.out.println("retStr =  " + retStr);
        PayResult payResult = JSON.parseObject(retStr, PayResult.class);
        if (null != payResult) {
            String data = payResult.getData();
            System.out.println("data =  " + data);
            if (null != data) {
                resp.setStatus(resp.SC_MOVED_TEMPORARILY);
                resp.setHeader("Location", payResult.getData());
            }
        }
    }


}
